from pymysql import Connection
import tools.llm as tl

# 获取到MySQL数据库的连接对象
conn = Connection(
    host='127.0.0.1',  # 主机名或IP地址
    port=3306,  # 端口号，默认3306
    user='root',  # MySQL账号
    password='123456',  # MySQL密码
    autocommit=True  # 设置自动提交(commit)
)
conn.select_db('ai_note')


def add_note(title, content):
    # 根据笔记的内容，生产一下笔记所属的分类，分类的长度最多有6个字符
    category = tl.GetNotTypePromptByAI(title, content)
    cursor = conn.cursor()
    # 插入数据到 notes 表中，判断一下title是否已经存在，如果存在就去更新，不存在就去新增数据
    cursor.execute("select * from notes where title=%s", title)
    if cursor.fetchone():
        if category != "":
            cursor.execute("update notes set content=%s, category=%s where title=%s", (content, category, title))
        else:
            cursor.execute("update notes set content=%s where title=%s", (content, title))
    else:
        if category != "":
            cursor.execute(
                "insert into notes(title,content,category) values(%s,%s,%s)",
                (title, content, category),
            )
        else:
            cursor.execute(
                "insert into notes(title,content) values(%s,%s)",
                (title, content),
            )


def get_notes(page=1):
    cursor = conn.cursor()
    cursor.execute("select * from notes limit %s,%s", (page * 10 - 10, page * 10))
    return cursor.fetchall()